<template>
  <avue-form :option="option"
             v-model="form"
             @tab-click="handleTabClick"
             @submit="handleSubmit"></avue-form>
</template>

<script>
import { getUserInfo, updatePassword } from '@/api/system/user';
import func from '@/utils/func';
import { validatenull } from '@/utils/validate';

export default {
  data() {
    return {
      index: 0,
      option: {
        column: [{
          label: '原密码',
          span: 8,
          row: true,
          type: 'password',
          prop: 'oldPassword',
          rules: [{ required: true, message: '请输入原密码', trigger: 'blur' }]
        }, {
          label: '新密码',
          span: 8,
          row: true,
          type: 'password',
          prop: 'newPassword',
          rules: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
            { min: 5, message: '新密码长度最少为5位', trigger: 'blur' }
          ]
        }, {
          label: '确认密码',
          span: 8,
          row: true,
          type: 'password',
          prop: 'newPassword1',
          rules: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
            { min: 5, message: '确认密码长度最少为5位', trigger: 'blur' }
          ]
        }]
      },
      form: {}
    };
  },
  created() {
    this.handleWitch();
  },
  methods: {
    handleSubmit(form, done) {
      updatePassword(form.oldPassword, form.newPassword, form.newPassword1).then(res => {
        if (res.data.success) {
          this.$message({
            type: 'success',
            message: '修改密码成功!'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg
          });
        }
        done();
      }, error => {
        window.console.log(error);
        done();
      });
    },
    handleWitch() {
      if (this.index === 0) {
        getUserInfo().then(res => {
          const user = res.data.data;
          this.form = {
            id: user.id,
            avatar: user.avatar,
            name: user.name,
            realName: user.realName,
            phone: user.phone,
            email: user.email
          };
        });
      }
    },
    handleTabClick(tabs) {
      console.log('tabsIndex：' + tabs.index);
      if (validatenull(tabs.index)) {
        return;
      }
      this.index = func.toInt(tabs.index, 0);
      this.handleWitch();
    }
  }
};
</script>
